
import math  
from loguru import logger
from cv.filter.filter import Filter

class ClassifyTH:

    __slots__ = ('ocr_raw_list','ocr_base_list','temp','temp_set','humi','humi_set','temp_num','temp_set_num','humi_num','humi_set_num','classify_flag','img_draw')

    def __init__(self,ocr_raw_list,ocr_base_list=None) -> None:
        self.ocr_raw_list = ocr_raw_list # 可能是温度或者湿度的字符串数组
        self.ocr_base_list = ocr_base_list # 用判断温度场还是湿度基准字符信息 

        self.temp = None 
        self.temp_num = None 

        self.temp_set = None
        self.temp_set_num = None

        self.humi = None
        self.humi_num = None

        self.humi_set = None
        self.humi_set_num = None


        self.classify_flag = False  # 当前ocr信息是否分类号的标志位

    def log_info(self):
        logger.warning('温度')
        print(self.temp_num)
        # print(Filter.get_pure_digit(self.temp.get('t')))

        logger.warning('温度设定')
        print(self.temp_set_num)
        # print(Filter.get_pure_digit(self.temp_set.get('t')))

        logger.warning('湿度')
        print(self.humi_num)
        # print(Filter.get_pure_digit(self.humi.get('t')))

        logger.warning('湿度设定')
        print(self.humi_set_num)
        # print(Filter.get_pure_digit(self.humi_set.get('t')))

    def classify_by_baseline(self):
        length = len(self.ocr_raw_list)

        temp_base = self.get_temp_base_v2() 
        temp_ocr_list = ClassifyTH.get_dis_list_to_base_with_point(base=temp_base,points=self.ocr_raw_list)
        sorted_temp_ocr_list = sorted(temp_ocr_list, key=lambda x: x['dis'])  
        logger.debug(sorted_temp_ocr_list);

        if length == 2 or 3:
            # 如果距离太大，则也判断不是温度
            
            self.temp_num = Filter.get_pure_digit(sorted_temp_ocr_list[0].get('t')) 
            self.temp_set_num = Filter.get_pure_digit(sorted_temp_ocr_list[1].get('t')) 
            self.classify_flag = True  
            return

        elif length == 4:
            # 如果距离太大，则也判断不是温度
            
            self.temp_num = Filter.get_pure_digit(sorted_temp_ocr_list[0].get('t')) 
            self.temp_set_num = Filter.get_pure_digit(sorted_temp_ocr_list[1].get('t')) 
            self.humi_num = Filter.get_pure_digit(sorted_temp_ocr_list[2].get('t')) 
            self.humi_set_num = Filter.get_pure_digit(sorted_temp_ocr_list[3].get('t')) 

            self.classify_flag = True  
            return










    def classify(self):
        length = len(self.ocr_raw_list)
        
        if length==3:
            self.classify_3_by_sorted()
            self.classify_flag = True  
            return

        elif length==4:
            result = any([True for item in self.ocr_raw_list if '0.0' == item['t'] or '00' in item['t']])  
            if result: 
                logger.debug('有4个值，但是有0.0，说明温度的实际值被拆分了,缩放图片重新识别')
                logger.debug(self.ocr_raw_list)
                self.classify_flag = False  
                return 

            self.classify_4()
            self.classify_flag = True

        elif length==2:
            logger.debug('有两个值，高斯模糊或者缩放一下，在重新识别')

            self.classify_flag = False  
            return
        else:

            self.classify_flag = False  
            return


        
    def classify_by_height(self):
        length = len(self.ocr_raw_list)

        if length==2:
            if self.ocr_raw_list[0].get('y') > self.ocr_raw_list[1].get('y'): 
                self.temp_num = Filter.get_pure_digit(self.ocr_raw_list[0].get('t')) 
                self.humi_num = Filter.get_pure_digit(self.ocr_raw_list[1].get('t')) 
            else:
                self.temp_num = Filter.get_pure_digit(self.ocr_raw_list[1].get('t')) 
                self.humi_num = Filter.get_pure_digit(self.ocr_raw_list[0].get('t')) 

            self.temp_set_num = ''
            self.humi_set_num = ''

            self.classify_flag = True  
        else:
            self.classify_flag = False  



    def classify_black_bg_white_temp_humi(self):
        length = len(self.ocr_raw_list)
        if length==1:
            self.temp_num = Filter.get_pure_digit(self.ocr_raw_list[0].get('t')) 
            self.classify_flag = True  
            return
        else:
            pass

        self.classify_flag = False  




         

    def classify_4(self):
        sorted_data = sorted(self.ocr_raw_list, key=lambda x: x['y'])  

        self.temp = sorted_data[0]
        self.temp_set = sorted_data[1]

        self.humi = sorted_data[2]
        self.humi_set = sorted_data[3]

        self.temp_num = Filter.get_pure_digit(sorted_data[0].get('t'))
        self.temp_set_num = Filter.get_pure_digit(sorted_data[1].get('t')) 

        self.humi_num = Filter.get_pure_digit(sorted_data[2].get('t')) 
        self.humi_set_num = Filter.get_pure_digit(sorted_data[3].get('t')) 


        

    def classify_3_by_sorted(self):
        sorted_data = sorted(self.ocr_raw_list, key=lambda x: x['y'])  
        if '0.0' in sorted_data[2].get('t') or '00' in sorted_data[2].get('t'):
            logger.debug('温度启用，湿度没启用')
            self.temp=sorted_data[0]
            self.temp_set=sorted_data[1]

            self.temp_num = Filter.get_pure_digit(sorted_data[0].get('t')) 
            self.temp_set_num = Filter.get_pure_digit(sorted_data[1].get('t')) 

        else:
            logger.debug('湿度启用，温度没启用')
            self.humi=sorted_data[0]
            self.humi_set=sorted_data[1]

            self.humi_num = Filter.get_pure_digit(sorted_data[0].get('t')) 
            self.humi_set_num = Filter.get_pure_digit(sorted_data[1].get('t')) 










           
    def classify_3(self):
        logger.debug('classify 3')
        idx = self.__detect_no_use()
        logger.debug(idx)
        if not idx:
            logger.debug('其他情况')
        else:
            logger.debug('温湿度，仅启用一个')
            flag,min_index = self.detect_humi_enable(idx)
            if flag:
                logger.debug('温度，没有启用')
            else:
                logger.debug('湿度，没有启用')
                self.humi_set = None
                self.humi = None
                self.ocr_raw_list.pop(idx)
                self.classify_temp()


    def classify_temp(self):
        """将温度分类成温度实际值和变化值
        """
        temp_base = self.get_temp_base() 
        dis_list = ClassifyTH.get_dis_list_to_base(base=temp_base,points=self.ocr_raw_list)
        min_idx = dis_list.index(min(dis_list))
        self.temp = self.ocr_raw_list[min_idx] 
        self.ocr_raw_list.pop(min_idx)
        self.temp_set = self.ocr_raw_list[0]



    @staticmethod
    def get_dis_list_to_base(base,points):
        dis_list = []
        for point in points:
            dis = ClassifyTH.get_distance(point1 = base,point2=point)
            dis_list.append(dis)
        return dis_list

    @staticmethod
    def get_dis_list_to_base_with_point(base,points):
        dis_list = []
        for point in points:
            dis = ClassifyTH.get_distance(point1 = base,point2=point)
            point['dis'] = dis
            dis_list.append(point)
        return dis_list


    def get_temp_base(self):
        temp_idx = [i for i, d in enumerate(self.ocr_base_list) if '溫度' or '温度' == d['t']]  
        if len(temp_idx)!=1:
            logger.debug('没有检测到温度基准')
            return None
        return self.ocr_base_list[temp_idx[0]] 

    def get_temp_base_v2(self):
        for i, d in enumerate(self.ocr_base_list):
            if d['t'] == '溫度' or '温度' :
                return self.ocr_base_list[i]

        logger.error('没有检测到温度基准')



        
    def detect_humi_enable(self,idx):
        ocr = self.ocr_raw_list[idx] 
        dis_list = self.get_distance_to_base_list(point=ocr)
        min_index = dis_list.index(min(dis_list))  
        label = self.ocr_base_list[min_index].get('t')
        if label == '濕度':
            logger.debug('湿度，没有启用')
            return False,min_index
        elif label == '溫度':
            logger.debug('温度，没有启用')
            return True,min_index


    def get_distance_to_base_list(self,point):
        dis_list = []
        for point_base in self.ocr_base_list: 
            dis = ClassifyTH.get_distance(point_base,point2=point)
            dis_list.append(dis)
        return dis_list
            
        

    
    def __detect_no_use(self):
        arr = self.ocr_raw_list
        idx = [i for i, x in enumerate(arr) if x['t'] == '0.0'][0]  
        return idx


    @staticmethod
    def get_distance(point1,point2):
        x1 = point1['x']  
        y1 = point1['y']  
        x2 = point2['x']  
        y2 = point2['y']  
        distance = math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)  
        return distance
        
        





